import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { loginCallback, toLogin } from "@/api/api";
// import Vconsole from 'vconsole'
// const vConsole = new Vconsole()
router.beforeEach((to, from, next) => {
	//  第一次进入项目
	document.title = '用心筹'
	const token = sessionStorage.getItem("token");
	//正式用code
	const code = getUrlParam("code");
	let state = to.path == '/' ? "STATE" : to.path.replace("/", "");
	//测试用code
	//const code = "081CPAV61XVRgO1CrpV61viAV61CPAV5";
	let url = "http://yongxinchou.com.cn/front/myIndex.html",
		appid = "wx2c31ac22d50b2954";
	if (to.path == '/Detail') {
		sessionStorage.setItem("id", to.query.id);
	}
	const aaa = getUrlParam("state");
	//微信授权登陆验证
	if (!code) {
		window.location.href =
			"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
			appid +
			"&redirect_uri=" +
			url +
			"&response_type=code&scope=snsapi_userinfo&state=" +
			state +
			"#wechat_redirect";
	} else if (!token) {
		//测试用登陆
		// toLogin().then(res => {
		// 	if (res.code == '0') {
		// 		sessionStorage.setItem("token", res.results.token);
		// 		const type = getUrlParam("state");
		// 		if (type == "Initiate") {
		// 			next({
		// 				path: '/Initiate',
		// 			})
		// 		} else if (type == "Detail") {
		// 			next({
		// 				path: '/Detail',
		// 				query: { id: sessionStorage.getItem("id") }
		// 			})
		// 		} else {
		// 			next();
		// 		}
		// 	}
		// })
		//正式用登陆
		loginCallback({ code: code })
			.then(res => {
				if (res.code == '0') {
					sessionStorage.setItem("token", res.results.token);
					const type = getUrlParam("state");
					if (type == "Initiate") {
						next({
							path: '/Initiate',
						})
					} else if (type == "Detail") {
						next({
							path: '/Detail',
							query: { id: sessionStorage.getItem("id") }
						})
					} else {
						next();
					}
				}
			})
	} else {
		next();
	}

});

function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var rrr = decodeURIComponent(window.location.search);
	var r = rrr.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}
new Vue({
	router,
	store,
	render: h => h(App)
}).$mount("#app");
//Vue.use(vConsole)